package com.chengxiaoxiao.libarypartner.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chengxiaoxiao.libarypartner.R;
import com.chengxiaoxiao.libarypartner.constants.Consrants;
import com.chengxiaoxiao.libarypartner.utils.ApiAddress;
import com.chengxiaoxiao.libarypartner.utils.LoadDialogUtils;
import com.chengxiaoxiao.libarypartner.utils.ToastUtils;
import com.chengxiaoxiao.libarypartner.utils.UserUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.image.SmartImageView;
import com.zxing.activity.CaptureActivity;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

public class ReturnsActivity extends Activity
{
    private LinearLayout lineBook;
    private TextView textStatus;

    private SmartImageView imageBook;
    private TextView textBookInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_returns);
        lineBook =(LinearLayout)findViewById(R.id.lineBook);
        textStatus = (TextView) findViewById(R.id.textStatus);
        imageBook = (SmartImageView) findViewById(R.id.imageBook);
        textBookInfo = (TextView) findViewById(R.id.textBookInfo);


    }

    /**
     * 扫描书籍背面ISBN
     * @param v
     */
    public void scan(View v)
    {
        Intent intent = new Intent(ReturnsActivity.this, CaptureActivity.class);
        startActivityForResult(intent, 0);
    }

    /**
     * 接收二维码的结果
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
        {
            /**
             * 获取扫描的条形码
             */
            String msg = data.getExtras().getString("result");

            lineBook.setVisibility(View.VISIBLE);

            textStatus.setText("状态：扫描完成");

            initBook(msg);

        }
    }

    /**
     * 还书
     * @param v
     */
    public void returnBook(View v)
    {
        LoadDialogUtils.show(ReturnsActivity.this,"","加载中...");
        AsyncHttpClient client = new AsyncHttpClient();

        RequestParams params = new RequestParams();
        params.add("userId", UserUtils.getNumber(ReturnsActivity.this));
        params.add("bookId",bookId+"");

        client.post(ApiAddress.getApiDomain() + "/client/ClientServlet?op=return",params, new AsyncHttpResponseHandler()
        {
            @Override
            public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody)
            {
                LoadDialogUtils.hidden();

                String body = new String(responseBody);

                //ToastUtils.makeText(LoginActivity.this,body);
                try
                {
                    JSONObject jsonObj = new JSONObject(body);
                    String status = jsonObj.getString(Consrants.JSON_RESPONSE_KEY_STATUS);
                    String msg = jsonObj.getString(Consrants.JSON_RESPONSE_KEY_ERRORMSG);

                    if ("error".equalsIgnoreCase(status))
                    {
                        ToastUtils.makeText(ReturnsActivity.this,"书籍信息验证错误，请确认书籍信息！");

                    }
                    else if("ok".equalsIgnoreCase(status))
                    {
                        new  AlertDialog.Builder(ReturnsActivity.this).setTitle("还书成功" ).setMessage("还书名称："+textBookInfo.getText())
                                .setPositiveButton("确定", new DialogInterface.OnClickListener()
                                {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which)
                                    {
                                        startActivity(new Intent(ReturnsActivity.this,MainActivity.class));
                                    }
                                })
                                .show();

                    }

                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
            {
                LoadDialogUtils.hidden();
                ToastUtils.makeText(getApplication(), "书籍信息验证错误，请确认书籍信息！");
            }
        });

    }


    int bookId = 0;
    /**
     * 加载书籍信息
     * @param msg
     */
    private void initBook(String msg)
    {
        final AsyncHttpClient client = new AsyncHttpClient();
        client.get(ApiAddress.getApiDomain() + "/client/ClientServlet?op=getBookByIsbn&isbn=" +msg , new AsyncHttpResponseHandler()
        {
            @Override
            public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody)
            {

                String body = new String(responseBody);
                try
                {
                    JSONObject jsonObj = new JSONObject(body);

                    int id = jsonObj.getInt("id");
                    String author = jsonObj.getString("author");
                    String bookName = jsonObj.getString("name");
                    int number = jsonObj.getInt("number");
                    String categporyName = jsonObj.getString("categoryName");
                    String publisherName = jsonObj.getString("publisherName");
                    String imagesPath = jsonObj.getString("imagesSrc");
                    String address = jsonObj.getString("address");

                    bookId = id;

                    //ToastUtils.makeText(ScanActivity.this,code);

                    imageBook.setImageUrl(imagesPath);
                    textBookInfo.setText("[" + bookName + "] " + author + " " + publisherName + " " + address);


                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
            {
                //LoadDialogUtils.hidden();
                ToastUtils.makeText(ReturnsActivity.this, "网络连接错误");
            }
        });


    }
}
